<template>
  <div>
    <el-dialog
      title="跟踪信息文件"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          @keyup.native.enter="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button
          type="primary"
          class="el-icon-plus add-btn"
          :disabled="listLoading"
          @click="handleAction('create', '添加')"
        >添加
        </el-button>
      </div>

      <el-table
        v-loading.fullscreen.lock="listLoading"
        :data="data"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @sort-change="handleSort"
      >
        <el-table-column align="center" label="文件链接" prop="download_link" />
        <el-table-column align="center" label="包含网站" prop="websites">
          <template slot-scope="scope">
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ scope.row.websites[0].domain }}<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="(item,index) in scope.row.websites" :key="item.id">{{ item.domain }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column align="center" label="start" prop="start" />
        <el-table-column align="center" label="end" prop="end" />
        <el-table-column align="center" label="创建时间" prop="create_at" />
        <el-table-column align="center" label="操作" width="400">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">重新生成</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <el-pagination
        v-if="data.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
      <el-dialog
        append-to-body
        title="生成新的paypal订单跟踪文件"
        width="80%"
        class="mt-dialog2"
        :visible.sync="innerDialogVisible"
        :close-on-click-modal="false"
      >

        <el-form v-if="this.action !=='delete'" :model="temp" label-position="left" label-width="80px">
          <el-form-item label="Paypal api账号">
            <el-input v-model="temp.paypal" />
          </el-form-item>
          <el-form-item label="指定网站" label-width="80px">
            <el-transfer
              v-model="temp.websites"
              filterable
              :filter-method="filterMethod"
              :titles="['可选站点', '已选站点']"
              filter-placeholder="输入搜索"
              :data="websites"
              :props="{
                key: 'id',
                label: 'domain'
              }"
            />
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="timerange"
              type="datetimerange"
              value-format="timestamp"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              :default-time="['0:00:00', '23:59:59']"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="innerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Delete, Put } from '@/api/orders/trackingfiles'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Trackingfiles',
  props: ['trackingfilesVisible'],
  data() {
    return {
      data: [],
      listLoading: true,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      websites: [],
      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        paypal: '',
        websites: [],
        start: '',
        end: ''
      },
      timerange: '',
      width: '',
      innerDialogVisible: false,
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime())
            start.setHours(0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天下班后',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            start.setHours(19, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '过去14天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14)
            start.setHours(0, 0, 0)
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近6个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            start.setHours(0, 0, 0)
            end.setHours(23, 59, 59)
            picker.$emit('pick', [start, end])
          }
        }
        ]
      }
    }
  },
  watch: {
    trackingfilesVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    }
  },
  created() {
    this.fetchWebsites()
  },
  methods: {
    filterMethod(query, item) {
      return item.domain.indexOf(query) > -1 || item.paypal_api_account.indexOf(query) > -1
    },
    resetTemp() {
      this.temp = {
        websites: []
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '新添加'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'edit':
          this.temp = Object.assign({}, row)
          this.confirm()
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.name}?`
          this.temp = Object.assign({}, row)
          break
      }
    },
    confirm() {
      const _data = this.temp
      if (this.timerange !== '') {
        this.temp.start = this.timerange ? this.timerange[0] : ''
        this.temp.end = this.timerange ? this.timerange[1] : ''
      }
      switch (this.action) {
        case 'create':
          Post(this.temp
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
          })
          break
        case
          'edit':
          Put(this.temp.id, this.temp).then((response) => {
            this.getList()
            this.$emit('reload')
            this.innerDialogVisible = false
            this.notify('发送成功，后台生成')
          })
          break
        case
          'delete'
          :
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // 获取站点
    fetchWebsites() {
      GetWebsite().then(response => {
        this.websites = response.data.data
        this.websiteLoading = false
      }).catch(e => {
        this.websiteLoading = false
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .top >>> .el-select .el-input {
    width: 350px;
  }

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .el-transfer-panel {
    width: 400px !important;
  }
  .app-container >>> .el-transfer-panel {
    width: 400px !important;
  }

  .mt-dialog2 >>> .el-transfer-panel {
     width: 400px !important;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 60px;
    padding-top: 5px;
  }
</style>
